<template>
	<div class="host">
		<HeaderLayout></HeaderLayout>
		<div class="box">
			<div class="content">
				<div
					@click="() => router.back()"
					style="background: #64bdff; max-width: max-content; padding: 5px 10px; color: white">
					返回
				</div>
				<div style="width: 100%; display: flex; justify-content: flex-end; padding: 30px 0">
					<el-select
						v-model="selectTimeInterval"
						filterable
						@change="handleSelectInterval"
						placeholder="Select"
						style="margin-right: 50px">
						<el-option
							v-for="item in options"
							:key="item.value"
							:label="item.label"
							:value="item.value" />
					</el-select>
					<div style="width: 30%">
						<el-date-picker
							v-model="selectDate"
							type="daterange"
							range-separator="-"
							:default-time="defaultPickerTime"
							start-placeholder="Start date"
							end-placeholder="End date"
							value-format="YYYY-MM-DD HH:mm:ss"
							@change="handleSelectDate"
							:disabled-date="
								(time) => {
									// 定义禁止选择的时间范围
									const now = new Date()
									const today = new Date(now.getFullYear(), now.getMonth(), now.getDate())
									const targetDate = new Date(time.getFullYear(), time.getMonth(), time.getDate())
									return targetDate > today // 禁用今天之前的日期
								}
							" />
					</div>
				</div>

				<div class="chartRef" style="position: relative">
					<div ref="hostLineChartRef" style="flex-grow: 1"></div>
				</div>
			</div>
		</div>
		<div style="margin: auto">
			<div style="width: 600px">
				<el-slider v-model="maxValue" range :max="800" @change="szz()"></el-slider>
			</div>
		</div>
	</div>
</template>

<script setup>
import { http } from '@/api/http.js'
import labTable from '@/mixins/table.json'
import { useRouter } from 'vue-router'
import { chunk } from '@/utils/utils.js'
import { routerPush, routerReplace, routerGo } from '@/plugins/index.js'
import {
	ENGINE_LEFT,
	ENGINE_RIGHT,
	ENGINE_LEFT_PW,
	ENGINE_RIGHT_PW,
	ENGINE_LEFT_ZC,
	ENGINE_RIGHT_ZC,
	ZC_LEN,
	PW_LEN,
	ENGINE_LEFT_SUPERCHARGER,
	ENGINE_RIGHT_SUPERCHARGER,
	ENGINE_LEFT_INFO,
	ENGINE_RIGHT_INFO,
	SUPERCHARGER_LEN
} from '@/utils/const.js'
import moment from 'moment'
let router = useRouter()
const maxValue = ref([0, 800])
const listMap = ref({})
// import dataJson from '@/mixins/data.json'
// let allData = inject('allData')
// let rightFields = {
// 	sup_fields: ENGINE_RIGHT_SUPERCHARGER,
// 	info_fields: ENGINE_RIGHT_INFO,
// 	zc_fields: ENGINE_RIGHT_ZC,
// 	pw_fields: ENGINE_RIGHT_PW,
// 	fields: [
// 		...ENGINE_RIGHT_PW,
// 		...ENGINE_RIGHT_ZC,
// 		...ENGINE_RIGHT_SUPERCHARGER,
// 		...ENGINE_RIGHT_INFO
// 	]
// }

// const getLocalUTCDate = ({ start, stop }) => {
// 	console.log('=======getlocalUTCDate')
// 	let seg_utc_start = moment(start).clone().utc().format()
// 	let seg_utc_end = moment(stop).clone().utc().format()
// 	return {
// 		seg_utc_start,
// 		seg_utc_end
// 	}
// }

const props = defineProps(['engine', 'field'])
let engine = ref(props.engine)
// let leftFields = {
// 	sup_fields: ENGINE_LEFT_SUPERCHARGER,
// 	info_fields: ENGINE_LEFT_INFO,
// 	zc_fields: ENGINE_LEFT_ZC,
// 	pw_fields: ENGINE_LEFT_PW,
// 	fields: [...ENGINE_LEFT_PW, ...ENGINE_LEFT_ZC, ...ENGINE_LEFT_SUPERCHARGER, ...ENGINE_LEFT_INFO]
// }

let fields = { LeftMain: labTable.left_main, RightMain: labTable.right_main, Hyb: labTable.hyb }
let fieldData = ref(fields[props.engine])
let timeInterval = ref([1, 2, 3, 15, 30, 45, 60])
let selectTimeInterval = ref(timeInterval.value[0])
const options = [...timeInterval.value.map((item) => (item = { label: item + '分', value: item }))]
// const formateParmasTimes = (seg_arr) => {
// 	return seg_arr
// 		.map((item) => (item = [Object.values(item)[1], Object.values(item)[3]].join('_')))
// 		.join(',')
// }
const defaultTime = {
	start: moment().startOf('day').format('YYYY-MM-DD HH:mm:ss'),
	stop: moment().startOf('day').format('YYYY-MM-DD HH:mm:ss'),
	intervalMinutes: timeInterval.value[0]
}

let parmas = reactive({
	// times: formateParmasTimes(segTime(defaultTime)),
	start: moment().startOf('day').clone().utc().format(),
	stop: moment().startOf('day').add(1, 'days').clone().utc().format(),
	time: selectTimeInterval,
	measurementName: engine.value,
	fields: props.field,
	bucketName:localStorage.getItem('bucketName')
})

const defaultPickerTime = ref([new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 0, 0, 0)])
// 使用函数生成时间段
// import dataJson from "@/mixins/test.json"
let Echarts = inject('$echarts')
let instanceEchartsList = ref(null)
const hostLineChartRef = ref(null)
let sethostLineChartRef = (el) => {
	hostLineChartRef.value.push(el)
}

const selectDate = ref([defaultTime.start, defaultTime.stop])
let setOption = (data, min, max) => {
	console.log(data, 'datadata=========>')
	return {
		tooltip: {
			trigger: 'axis',
			axisPointer: {
				show: true,
				type: 'cross'
			},
			borderWidth: 1,
			borderColor: '#ccc',
			padding: 10,
			textStyle: {
				color: '#000'
			}
		},
		legend: {
			left: 120
		},
		dataZoom: [
			{
				type: 'inside',
				start: 100,
				end: 0
			},
			{
				show: true,
				type: 'slider'
			}
		],
		axisPointer: {
			link: [
				{
					xAxisIndex: 'all'
				}
			],
			label: {
				backgroundColor: '#777'
			}
		},
		xAxis: [
			{
				type: 'time',
				data: data.volumns
			}
		],
		yAxis: [
			{
				scale: true,
				splitArea: {
					show: true
				},
				min: min || 0,
				max: max || null
			}
		],
		series: [...data.values]
	}
}

let setTitle = (title) => {
	return {
		show: true,
		left: 'center',
		text: title,
		textStyle: {
			fontSize: 25
		}
	}
}
const szz = () => {
	const data = formatData1(listMap.value)
	console.log(data, 'szz=========>')
	setChart(data, maxValue.value[0], maxValue.value[1])
}
const setChart = (data, min, max) => {
	let option = setOption(data, min, max)
	if (!instanceEchartsList.value) {
		instanceEchartsList.value = markRaw(
			Echarts.init(hostLineChartRef.value, null, {
				renderer: 'canvas',
				useDirtyRect: false
			})
		)
	}
	instanceEchartsList.value.setOption(option, true)
	instanceEchartsList.value.hideLoading()
}

function utcTranLocalTime(value, format = 'YYYY-MM-DD HH:mm:ss') {
	return moment.utc(value).local().format('YYYY-MM-DD HH:mm:ss')
}
const formatData = (data) => {
	return data.map((item) => {
		return [utcTranLocalTime(item.time), item.avg]
	})
}

const formatData1 = (data) => {
	let values = []
	Object.keys(data).forEach((key) => {
		values.push({
			data: formatData(data[key]),
			type: 'line',
			smooth: true,
			name: fieldData.value[key].name
		})
	})

	let volumns = []
	for (let v of values[0].data) {
		let vl = [...v]
		vl[1] = 1000
		volumns.push(vl)
	}
	return {
		values: values,
		volumns: volumns
	}
}

// const splitData = (rowData) => {
// 	var categoryData = []
// 	var values = []
// 	var volumns = []
// 	for (var i = 0; i < rowData.length; i++) {
// 		categoryData.push(rowData[i][0]) // 假设日期是第一个元素
// 		values.push(rowData[i]) // 开盘、最高、最低、收盘价
// 		volumns.push([rowData[i][0], 1000]) // 第六个元素是交易量
// 	}
// 	return {
// 		categoryData: categoryData,
// 		values: values,
// 		volumns: volumns
// 	}
// }
const setLoding = () => {
	if (!instanceEchartsList.value) {
		instanceEchartsList.value = markRaw(
			Echarts.init(hostLineChartRef.value, null, {
				renderer: 'canvas',
				useDirtyRect: false
			})
		)
	}
	instanceEchartsList.value.showLoading()
}
let fetchDataList = async () => {
	setLoding()
	let { list } = await http('POST')('/postIntervalWind', parmas)
	listMap.value = list
	const data = formatData1(list)
	setChart(data)
}

const handleSelectDate = async (date) => {
	let [startTime, endTime] = date
	if (startTime > endTime) {
		throw new Error('结束时间必须在开始时间之后或与之相同')
	}
	const start = moment(startTime, 'YYYY-MM-DD HH:mm:ss').clone().utc().format()
	const stop = moment(endTime, 'YYYY-MM-DD HH:mm:ss').add(1, 'days').clone().utc().format()
	parmas.start = start
	parmas.stop = stop
	await fetchDataList()
}

const handleSelectInterval = async (interval) => {
	parmas.time = interval
	await fetchDataList()
}
onMounted(async () => {
	document.body.style.zoom = ''
	await fetchDataList()
})
</script>

<style scoped lang="scss">
.host {
	height: 100vh;
	display: flex;
	flex-direction: column;
	.box {
		height: 100%;
		width: 100%;
		display: flex;
		box-sizing: border-box;
		padding: 15px;
		// background: #1a1918;
	}
	.content {
		width: 100%;
		display: flex;
		flex-direction: column;
		.chartRef {
			display: flex;
			flex-direction: column;
			flex: 1;
			height: 100%;
		}
		.detail {
			width: 50%;
			height: 100%;
			display: flex;
			flex-direction: column;
			.cargin {
				display: flex;
				justify-content: end;
				span {
					cursor: pointer;
					margin-left: 15px;
				}
			}
			.content {
				flex: 1;
				width: 100%;
			}
		}
	}
	.panel {
		width: 0%;
	}
}

// .btn-group{
//     display: flex;
//     margin: 0 auto;
// // }
// .host {
// 	height: 100%;
// 	display: flex;
// 	flex-wrap: wrap;
// 	background: rgb(45, 73, 97);
// 	& > div {
// 		height: 50%;
// 		width: 450px;
// 	}
// }
// :deep(.el-button--large.is-round) {
// 	padding: 12px 32px;
// }
</style>
